﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Web.DynamicData;
using System.Web.UI;
using System.Web.UI.WebControls;
using NotAClue.Web.DynamicData;
using NotAClue.Web;

namespace DD_Extensions
{
    public partial class BooleanCheckBoxFilter : System.Web.DynamicData.QueryableFilterUserControl
    {
        private const string NullValueString = "[null]";
        public override Control FilterControl
        {
            get { return CheckBox1; }
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            // set filters visibility
            this.SetFilterVisibility(Column);

            if (!Column.ColumnType.Equals(typeof(bool)))
                throw new InvalidOperationException(String.Format("A boolean filter was loaded for column '{0}' but the column has an incompatible type '{1}'.", Column.Name, Column.ColumnType));

            if (!Page.IsPostBack)
            {
                if (!Column.IsRequired)
                    throw new InvalidOperationException("Boolean CheckBox filter must be used with a none nullable field.");

                // Set the initial value if there is one
                Boolean initialValue = false;
                var defaultValue = this.SetFilterDefaultValue(Column);
                if (!String.IsNullOrEmpty(defaultValue) && Boolean.TryParse(defaultValue, out initialValue))
                    CheckBox1.Checked = initialValue;
                

            }
            Label1.Text = Column.DisplayName;
        }

        public override IQueryable GetQueryable(IQueryable source)
        {
            string selectedValue = CheckBox1.Checked ? Boolean.TrueString : Boolean.FalseString;
            if (String.IsNullOrEmpty(selectedValue))
                return source;

            object value = selectedValue;
            if (selectedValue == NullValueString)
                value = null;

            if (DefaultValues != null)
                DefaultValues[Column.Name] = value;

            return ApplyEqualityFilter(source, Column.Name, value);
        }

        protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
        {
            OnFilterChanged();

            Page.AddFilterValueToSession(Column, CheckBox1.Checked.ToString());
        }
    }
}
